/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.gt.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.constant.Constant;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.gt.entity.GtCompany;
import com.thinkgem.jeesite.modules.gt.entity.GtCompanyPeople;
import com.thinkgem.jeesite.modules.gt.entity.GtCountry;
import com.thinkgem.jeesite.modules.gt.entity.GtCountryInfo;
import com.thinkgem.jeesite.modules.gt.entity.GtForest;
import com.thinkgem.jeesite.modules.gt.entity.GtForestPeople;
import com.thinkgem.jeesite.modules.gt.entity.GtInfoDeliver;
import com.thinkgem.jeesite.modules.gt.entity.GtPolicy;
import com.thinkgem.jeesite.modules.gt.entity.GtPolicyPeople;
import com.thinkgem.jeesite.modules.gt.entity.GtPostPeople;
import com.thinkgem.jeesite.modules.gt.entity.GtTecClear;
import com.thinkgem.jeesite.modules.gt.entity.GtTrain;
import com.thinkgem.jeesite.modules.gt.entity.GtTrainPeople;
import com.thinkgem.jeesite.modules.gt.service.GtCompanyPeopleService;
import com.thinkgem.jeesite.modules.gt.service.GtCompanyService;
import com.thinkgem.jeesite.modules.gt.service.GtCountryInfoService;
import com.thinkgem.jeesite.modules.gt.service.GtCountryService;
import com.thinkgem.jeesite.modules.gt.service.GtForestPeopleService;
import com.thinkgem.jeesite.modules.gt.service.GtForestService;
import com.thinkgem.jeesite.modules.gt.service.GtInfoDeliverService;
import com.thinkgem.jeesite.modules.gt.service.GtPolicyPeopleService;
import com.thinkgem.jeesite.modules.gt.service.GtPolicyService;
import com.thinkgem.jeesite.modules.gt.service.GtPostPeopleService;
import com.thinkgem.jeesite.modules.gt.service.GtTecClearService;
import com.thinkgem.jeesite.modules.gt.service.GtTrainPeopleService;
import com.thinkgem.jeesite.modules.gt.service.GtTrainService;
import com.thinkgem.jeesite.modules.sys.entity.Area;
import com.thinkgem.jeesite.modules.sys.service.AreaService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 信息宣传Controller
 * @author zad
 * @version 2018-03-26
 */
@Controller
@RequestMapping(value = "${frontPath}/gt/gtDownLoad")
public class GtDownLoadController extends BaseController {

	@Autowired
	private GtInfoDeliverService gtInfoDeliverService;
	@Autowired
	private GtForestService gtForestService;
	@Autowired
	private GtForestPeopleService gtForestPeopleService;
	@Autowired
	private GtPolicyService gtPolicyService;
	@Autowired
	private GtPolicyPeopleService gtPolicyPeopleService;
	@Autowired
	private GtCountryInfoService gtCountryInfoService;
	@Autowired
	private GtCountryService gtCountryService;
	@Autowired
	private GtTrainService gtTrainService;
	@Autowired
	private GtTrainPeopleService gtTrainPeopleService;
	@Autowired
	private GtTecClearService gtTecClearService;
	@Autowired
	private GtPostPeopleService gtPostPeopleService;
	@Autowired
	private GtCompanyService gtCompanyService;
	@Autowired
	private GtCompanyPeopleService gtCompanyPeopleService;
	@Autowired
	private AreaService areaService;
	
	
	@RequestMapping(value = {"toDownLoad", ""})
	public String toDownLoad(String menuId, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		model.addAttribute("menuId", menuId);
		// 省级账号是需要查询地市信息，按照地市下载
		if(Constant.Area.AREA_TYPE_PROVINCE.equals(UserUtils.getUser().getArea().getType()))
		{
			Area param = new Area();
			Area p = new Area();
			p.setCode(UserUtils.getUser().getArea().getCode());
			param.setParent(p);
			param.setType(Constant.Area.AREA_TYPE_REGION);
			List<Area> regions = this.areaService.findList(param);
			model.addAttribute("regions", regions);
		}
		
		return "modules/gt/basic/gtDownLoad";
	}
	@RequestMapping(value = {"gtImport", ""})
	public String gtImport(String menuId,String type, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		model.addAttribute("menuId", menuId);
		
		return "modules/gt/basic/gtImport";
	}
	
	@RequestMapping(value = {"gtImportFile", ""})
	public String gtImportFile(String menuId,String type, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		model.addAttribute("menuId", menuId);
		String title = "经济林扶贫信息";
		// 经济林
		if("forest".equals(type))
		{
			title = "经济林扶贫信息";
		}else if("country".equals(type))
		{
			title = "技术培训信息";
		}else if("train".equals(type))
		{
			title = "技术培训信息";
		}else if("clear".equals(type))
		{
			title = "技术明白人信息";
		}else if("post".equals(type))
		{
			title = "护林员岗位信息";
		}else if("company".equals(type))
		{
			title = "龙头企业（合作社）信息";
		}else if("policy".equals(type))
		{
			title = "林业政策扶贫信息";
		}else if("deliver".equals(type))
		{
			title = "信息宣传";
		}
		
		model.addAttribute("title", title);
		model.addAttribute("type", type);
		
		return "modules/gt/basic/gtImportFile";
	}
	
	/**
     * 导入模板下载
     */
    @RequestMapping("downLoadTemplate")
    public void downLoadTemplate(HttpServletRequest request,String type, HttpServletResponse response) throws IOException{
    	 String templatePath = request.getSession().getServletContext().getRealPath("/template");
	     // String path = templatePath+"/奖品信息导入模板.xlsx"; 
    	 String path = templatePath+"/" + Global.getConfig("forestImportTemplate");
    	 if("country".equals(type))
    	 {
    		 path = templatePath+"/" + Global.getConfig("countryImportTemplate");
    	 }else if("train".equals(type))
    	 {
    		 path = templatePath+"/" + Global.getConfig("trainImportTemplate");
    	 }else if("clear".equals(type))
    	 {
    		 path = templatePath+"/" + Global.getConfig("clearImportTemplate");
    	 }else if("post".equals(type))
    	 {
    		 path = templatePath+"/" + Global.getConfig("postImportTemplate");
    	 }else if("company".equals(type))
    	 {
    		 path = templatePath+"/" + Global.getConfig("companyImportTemplate");
    	 }else if("policy".equals(type))
    	 {
    		 path = templatePath+"/" + Global.getConfig("policyImportTemplate");
    	 }else if("deliver".equals(type))
    	 {
    		 path = templatePath+"/" + Global.getConfig("deliverImportTemplate");
    	 }
    	 
    	File file = new File(path);// path是根据日志路径和文件名拼接出来的
    	if(file.exists()){
    		String filename = file.getName();// 获取日志文件名称
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            os.write(buffer);// 输出文件
            os.flush();
            os.close();
            request.setAttribute("title", "用户" + UserUtils.getUser().getLoginName() + "下载了模板：" + type);
    	}else{
    		System.out.println("没有找到文件");
    	}
    
    }
    
    /**
     * 信息导入
     */
    // @RequiresPermissions("ems:batch:import")
	@RequestMapping(value = "import")
	public String doBatchImport(@RequestParam(value = "batchFile", required = false) MultipartFile batchFile,
			String type,HttpServletRequest request, HttpServletResponse response, Model model) {
		String msg = "";
		boolean rs = true;
		
        
        // 没有帮扶带动人信息或者没有覆盖村信息
        // String noHelpMsg = null;
        // 所填区域不是乡镇级别
        // String notTownAreaMsg = null;
        
        
        
		if (batchFile != null) {
            try {
                InputStream is = batchFile.getInputStream();
                Workbook workBook = null;
                try{
                	workBook = new XSSFWorkbook(is);
                }catch(Exception e){
                	POIFSFileSystem fs = new POIFSFileSystem(is);
                	workBook = new HSSFWorkbook(fs);
                }
                XSSFSheet sheet;// = workbook.getSheetAt(index);
                
                // for(int i = 0; i < workBook.getNumberOfSheets(); i ++){
                	sheet=(XSSFSheet)workBook.getSheetAt(0);
	            
                if("forest".equals(type))
                {
                	msg = this.importForest(sheet);
                }else if("country".equals(type))
                {
                	msg = this.importCountry(sheet);
                }else if("train".equals(type))
                {
                	msg = this.importTrain(sheet);
                }else if("clear".equals(type))
                {
                	msg = this.importClear(sheet);
                }else if("post".equals(type))
                {
                	msg = this.importPost(sheet);
                }else if("company".equals(type))
                {
                	msg = this.importCompany(sheet);
                }else if("policy".equals(type))
                {
                	msg = this.importPolicy(sheet);
                }else if("deliver".equals(type))
                {
                	msg = this.importDeliver(sheet);
                }
                
                
                request.setAttribute("title", "用户" + UserUtils.getUser().getLoginName() + "导入了数据：" + type);
	                
                //}
            } catch (IOException e) {
            	e.printStackTrace();
            	rs = false;
            	msg = "导入失败。" + msg + e.getMessage();
            } catch (Exception e) {
            	rs = false;
            	msg = "导入失败。" + msg + e.getMessage();
            	e.printStackTrace();
            }
        }
		
		
		// request.setAttribute("msg", msg);
		model.addAttribute("message", msg);
		model.addAttribute("rs", rs);
		// return "modules/sys/sysIndex";
		return "modules/gt/basic/gtImportFile";
	}
	
	// 经济林扶贫导入
	public String importForest(XSSFSheet sheet)
	{
		String msg = "";
		
		// 没有帮扶带动人信息或者没有覆盖村信息
        String noHelpMsg = null;
        // 所填区域不是乡镇级别
        String notTownAreaMsg = null;
        
		//创建行和列
        XSSFRow row;
		List<GtForestPeople> forestPeopleList = new ArrayList<GtForestPeople>();
		GtForest forest = null;
		
		// 经济林不做保存
		boolean isContinue = false;
		//sheet.getLastRowNum()
        for (int j = 4; j <= sheet.getLastRowNum(); j++) {
            row = sheet.getRow(j);
            if(null == row)
            {
            	continue;
            }
            String areaId = null == row.getCell(1) ? null : row.getCell(1).toString().trim();
            
            // 类型：forest：经济林；空：经济林帮扶带动人口信息
            String forestType = null == row.getCell(0) ? null : row.getCell(0).toString().trim();
            // 该条信息为经济林
            if("forest".equals(forestType))
            {
            	XSSFRow rowNext = sheet.getRow(j + 1);
            	String forestTypeNext = null;
            	if(null != rowNext)
            	{
            		forestTypeNext = null == rowNext.getCell(0) ? null : rowNext.getCell(0).toString().trim();
            	}
            	
            	// 下一条不存在或者下一条也为经济林时，表示本条经济林没有帮扶带动人信息，所以本条经济林不做保存
            	if(null == rowNext || "forest".equals(forestTypeNext))
            	{
            		if(null == noHelpMsg)
                	{
            			noHelpMsg = "第" + (j+1) + "行(区域编号：" + areaId + ")";
                	}
                	else
                	{
                		noHelpMsg += "," + (j + 1) + "行(区域编号：" + areaId + ")";
                	}
            		
            		continue;
            	}
            	// 该条为经济林时，保存所有上一次的扶贫人信息
            	if(null != forestPeopleList && forestPeopleList.size() > 0)
                {
                	 this.gtForestPeopleService.insertList(forestPeopleList);
                	 forestPeopleList = new ArrayList<GtForestPeople>();
                }
            	
            	Area area = this.areaService.get(areaId);
            	//不是乡镇级区域不做处理
            	if(!Constant.Area.AREA_TYPE_TOWN.equals(area.getType()))
                {
                	if(null == notTownAreaMsg)
                	{
                		notTownAreaMsg = "第" + (j+1) + "行(区域编号：" + areaId + ")";
                	}
                	else
                	{
                		notTownAreaMsg += "," + (j + 1) + "行(区域编号：" + areaId + ")";
                	}
                	
                	isContinue = true;
                	continue;
                }
            	else
            	{
            		isContinue = false;
            	}
            	
            	if(null == forest)
            	{
            		forest = new GtForest();
            	}
            	if(null == forest.getArea())
            	{
            		Area forestArea = new Area();
                	forest.setArea(forestArea);
            	}
            	
            	
            	String forestAddr = null == row.getCell(2) ? null : row.getCell(2).toString().trim();
            	String forestArea = null == row.getCell(3) ? null : row.getCell(3).toString().trim();
            	String treeType = null == row.getCell(4) ? null : row.getCell(4).toString().trim();
            	forest.setIsNewRecord(true);
            	forest.setId(IdGen.uuid());
            	forest.setArea(area);
            	forest.setAddress(forestAddr);
            	forest.setForestArea(Double.parseDouble(forestArea));
            	forest.setTreeType(treeType);
            	forest.setCreateDate(new Date());
            	forest.setCreateBy(UserUtils.getUser());
            	forest.setUpdateBy(UserUtils.getUser());
            	this.gtForestService.save(forest);
            	
            }
            else
            {
            	// 若经济林跳过，则其下面的所有帮扶带动人都跳过
            	if(isContinue)
            	{
            		continue;
            	}
            	// 经济林帮扶带动人口
            	String name = null == row.getCell(1) ? null : row.getCell(1).toString().trim();
            	
            	if(null == name || "".equals(name))
            	{
            		System.out.println(j);
            		continue;
            	}
            	
            	String isHolder = null == row.getCell(2) ? null : row.getCell(2).toString().trim();
            	
            	if(isHolder.length() > 1)
            	{
            		isHolder = isHolder.substring(0, 1);
            	}
            	String idCard = null == row.getCell(3) ? null : row.getCell(3).toString().trim();
            	
            	
            	String addr = null == row.getCell(4) ? null : row.getCell(4).toString().trim();
            	String helpType = null == row.getCell(5) ? null : row.getCell(5).toString().trim();
            	if(helpType.indexOf(".") > -1)
            	{
            		helpType = helpType.substring(0, 1);
            	}
            	helpType = helpType.replace("，", ",");
            	String helpOther = null == row.getCell(6) ? null : row.getCell(6).toString().trim();
            	GtForestPeople forestPeople = new GtForestPeople();
            	forestPeople.setId(IdGen.uuid());
            	forestPeople.setForest(forest);
            	forestPeople.setCreateBy(UserUtils.getUser());
            	forestPeople.setUpdateBy(UserUtils.getUser());
            	forestPeople.setName(name);
            	forestPeople.setIsHolder(isHolder);
            	forestPeople.setIdcard(idCard);
            	forestPeople.setAddress(addr);
            	forestPeople.setHelpType(helpType);
            	forestPeople.setCreateDate(new Date());
            	if("o".equals(helpType))
            	{
            		forestPeople.setHelpOther(helpOther);
            	}
            	forestPeopleList.add(forestPeople);
            	
            	if(forestPeopleList.size() > 500)
                {
                	 this.gtForestPeopleService.insertList(forestPeopleList);
                	 forestPeopleList = new ArrayList<GtForestPeople>();
                }
            }
            
        }
        
        if(null != forestPeopleList && forestPeopleList.size() > 0)
        {
        	 this.gtForestPeopleService.insertList(forestPeopleList);
        }
        msg = "导入成功。";
        if(null != notTownAreaMsg)
		{
			msg += notTownAreaMsg + "经济林信息的区域编码不是乡镇级别，不做导入处理，其所属帮扶带动人口信息也不做导入处理。";
		}
        if(null != noHelpMsg)
		{
			msg += noHelpMsg + "经济林信息无帮扶带动人口信息，不做导入处理。";
		}
        return msg;
	}
	
	// 林业政策扶贫导入
	public String importPolicy(XSSFSheet sheet)
	{
		String msg = "";
		// 没有帮扶带动人信息或者没有覆盖村信息
        String noHelpMsg = null;
		//创建行和列
        XSSFRow row;
		List<GtPolicyPeople> policyPeopleList = new ArrayList<GtPolicyPeople>();
		GtPolicy policy = null;
		
		// 林业政策不做保存
		// boolean isContinue = false;
        for (int j = 4; j <= sheet.getLastRowNum(); j++) {
            row = sheet.getRow(j);
            
            String areaId = null == row.getCell(1) ? null : row.getCell(1).toString().trim();
            // 类型：policy：林业政策
            String policyType = null == row.getCell(0) ? null : row.getCell(0).toString().trim();
            // 该条信息为林业政策
            if("policy".equals(policyType))
            {
            	
            	XSSFRow rowNext = sheet.getRow(j + 1);
            	String policyTypeNext = null;
            	if(null != rowNext)
            	{
            		policyTypeNext = null == rowNext.getCell(0) ? null : rowNext.getCell(0).toString().trim();
            	}
            	
            	// 下一条不存在或者下一条也为经济林时，表示本条经济林没有帮扶带动人信息，所以本条经济林不做保存
            	if(null == rowNext || "policy".equals(policyTypeNext))
            	{
            		if(null == noHelpMsg)
                	{
            			noHelpMsg = "第" + (j+1) + "行(区域编号：" + areaId + ")";
                	}
                	else
                	{
                		noHelpMsg += "," + (j + 1) + "行(区域编号：" + areaId + ")";
                	}
            		
            		continue;
            	}
            	
            	// 该条为林业政策时，保存所有上一次的扶贫人信息
            	if(null != policyPeopleList && policyPeopleList.size() > 0)
                {
                	 this.gtPolicyPeopleService.insertList(policyPeopleList);
                	 policyPeopleList = new ArrayList<GtPolicyPeople>();
                }
            	
            	Area area = this.areaService.get(areaId);
            	
            	if(null == policy)
            	{
            		policy = new GtPolicy();
            	}
            	if(null == policy.getArea())
            	{
            		Area policyArea = new Area();
                	policy.setArea(policyArea);
            	}
            	
            	
            	String policyName = null == row.getCell(2) ? null : row.getCell(2).toString().trim();
            	policy.setIsNewRecord(true);
            	policy.setId(IdGen.uuid());
            	policy.setArea(area);
            	policy.setName(policyName);
            	policy.setCreateBy(UserUtils.getUser());
            	policy.setUpdateBy(UserUtils.getUser());
            	policy.setCreateDate(new Date());
            	this.gtPolicyService.save(policy);
            	
            }
            else
            {
            	// 林业政策帮扶带动人口
            	String name = null == row.getCell(1) ? null : row.getCell(1).toString().trim();
            	if(null == name || "".equals(name))
            	{
	            	System.out.println("----------"+j);
	            	continue;
            	}
            	String isHolder = null == row.getCell(2) ? null : row.getCell(2).toString().trim();
            	if(isHolder.length() > 1)
            	{
            		isHolder = isHolder.substring(0, 1);
            	}
            	String idCard = null == row.getCell(3) ? null : row.getCell(3).toString().trim();
            	if(idCard.length() > 22)
            	{
            		idCard = idCard.substring(0, 22);
            	}
            	String addr = null == row.getCell(4) ? null : row.getCell(4).toString().trim();
            	String helpType = null == row.getCell(5) ? null : row.getCell(5).toString().trim();
            	if(helpType.indexOf(".") > -1)
            	{
            		helpType = helpType.substring(0, 1);
            	}
            	helpType = helpType.replace("，", ",");
            	String helpOther = null == row.getCell(6) ? null : row.getCell(6).toString().trim();
            	GtPolicyPeople policyPeople = new GtPolicyPeople();
            	policyPeople.setId(IdGen.uuid());
            	policyPeople.setPolicy(policy);
            	policyPeople.setCreateBy(UserUtils.getUser());
            	policyPeople.setUpdateBy(UserUtils.getUser());
            	policyPeople.setName(name);
            	policyPeople.setIsHolder(isHolder);
            	policyPeople.setIdcard(idCard);
            	policyPeople.setAddress(addr);
            	policyPeople.setHelpType(helpType);
            	policyPeople.setCreateDate(new Date());
            	if("o".equals(helpType))
            	{
            		policyPeople.setHelpOther(helpOther);
            	}
            	policyPeopleList.add(policyPeople);
            	
            	if(policyPeopleList.size() > 500)
                {
                	 this.gtPolicyPeopleService.insertList(policyPeopleList);
                	 policyPeopleList = new ArrayList<GtPolicyPeople>();
                }
            }
            
        }
        
        if(null != policyPeopleList && policyPeopleList.size() > 0)
        {
        	 this.gtPolicyPeopleService.insertList(policyPeopleList);
        }
        msg = "导入成功。";
        /*if(null != notTownAreaMsg)
		{
			msg += notTownAreaMsg + "林业政策信息的区域编码不是乡镇级别，不做导入处理；其所属帮扶带动人口信息也不做导入处理。";
		}*/
        
        if(null != noHelpMsg)
		{
			msg += noHelpMsg + "林业政策信息无帮扶带动人口信息，不做导入处理。";
		}
        
        return msg;
	}
	
	
	// 科技下乡扶贫信息导入
	public String importCountry(XSSFSheet sheet)
	{
		String msg = "";
		// 没有帮扶带动人信息或者没有覆盖村信息
        String noHelpMsg = null;
		//创建行和列
        XSSFRow row;
		List<GtCountry> countryList = new ArrayList<GtCountry>();
		GtCountryInfo countryInfo = null;
		
		// 科技下乡不做保存
		// boolean isContinue = false;
        for (int j = 4; j <= sheet.getLastRowNum(); j++) {
            row = sheet.getRow(j);
            
            String areaId = null == row.getCell(1) ? null : row.getCell(1).toString().trim();
            // 类型：country：科技下乡
            String countryType = null == row.getCell(0) ? null : row.getCell(0).toString().trim();
            // 该条信息为科技下乡
            if("country".equals(countryType))
            {
            	
            	XSSFRow rowNext = sheet.getRow(j + 1);
            	String countryTypeNext = null;
            	if(null != rowNext)
            	{
            		countryTypeNext = null == rowNext.getCell(0) ? null : rowNext.getCell(0).toString().trim();
            	}
            	
            	// 下一条不存在或者下一条也为经济林时，表示本条经济林没有帮扶带动人信息，所以本条经济林不做保存
            	if(null == rowNext || "country".equals(countryTypeNext))
            	{
            		if(null == noHelpMsg)
                	{
            			noHelpMsg = "第" + (j+1) + "行(区域编号：" + areaId + ")";
                	}
                	else
                	{
                		noHelpMsg += "," + (j + 1) + "行(区域编号：" + areaId + ")";
                	}
            		
            		continue;
            	}
            	
            	// 该条为科技下乡时，保存所有上一次的扶贫人信息
            	if(null != countryList && countryList.size() > 0)
                {
                	 this.gtCountryService.insertList(countryList);
                	 countryList = new ArrayList<GtCountry>();
                }
            	
            	Area area = this.areaService.get(areaId);
            	
            	if(null == countryInfo)
            	{
            		countryInfo = new GtCountryInfo();
            	}
            	if(null == countryInfo.getArea())
            	{
            		Area countryArea = new Area();
                	countryInfo.setArea(countryArea);
            	}
            	
            	
            	String time = null == row.getCell(2) ? null : row.getCell(2).toString().trim();
            	String content = null == row.getCell(3) ? null : row.getCell(3).toString().trim();
            	countryInfo.setIsNewRecord(true);
            	countryInfo.setId(IdGen.uuid());
            	countryInfo.setArea(area);
            	try {
					countryInfo.setTime(DateUtils.parseDate(time, "yyyy-MM-dd HH:mm:ss"));
				} catch (ParseException e) {
					e.printStackTrace();
				}
            	countryInfo.setContent(content);
            	countryInfo.setCreateBy(UserUtils.getUser());
            	countryInfo.setUpdateBy(UserUtils.getUser());
            	countryInfo.setCreateDate(new Date());
            	this.gtCountryInfoService.save(countryInfo);
            	
            }
            else
            {
            	// 科技下乡帮扶带动村
            	String name = null == row.getCell(1) ? null : row.getCell(1).toString().trim();
            	if(null == name || "".equals(name))
            	{
            		continue;
            	}
            	GtCountry country = new GtCountry();
            	country.setId(IdGen.uuid());
            	country.setCountryInfo(countryInfo);
            	country.setCreateBy(UserUtils.getUser());
            	country.setUpdateBy(UserUtils.getUser());
            	country.setName(name);
            	country.setCreateDate(new Date());
            	countryList.add(country);
            	
            	if(countryList.size() > 500)
                {
                	 this.gtCountryService.insertList(countryList);
                	 countryList = new ArrayList<GtCountry>();
                }
            }
            
        }
        
        if(null != countryList && countryList.size() > 0)
        {
        	 this.gtCountryService.insertList(countryList);
        }
        msg = "导入成功。";
        /*if(null != notTownAreaMsg)
		{
			msg += notTownAreaMsg + "科技下乡信息的区域编码不是乡镇级别，不做导入处理；其所属帮扶带动人口信息也不做导入处理。";
		}*/
        
        if(null != noHelpMsg)
		{
			msg += noHelpMsg + "科技下乡信息无帮扶带动村，不做导入处理。";
		}
        
        return msg;
	}
	
	
	// 技术培训信息导入
	public String importTrain(XSSFSheet sheet)
	{
		String msg = "";
		// 没有帮扶带动人信息或者没有覆盖村信息
        String noHelpMsg = null;
		//创建行和列
        XSSFRow row;
		List<GtTrainPeople> trainList = new ArrayList<GtTrainPeople>();
		GtTrain trainInfo = null;
		
		// 技术培训不做保存
		// boolean isContinue = false;
        for (int j = 4; j <= sheet.getLastRowNum(); j++) {
            row = sheet.getRow(j);
            
            String areaId = null == row.getCell(1) ? null : row.getCell(1).toString().trim();
            // 类型：train：技术培训
            String trainType = null == row.getCell(0) ? null : row.getCell(0).toString().trim();
            // 该条信息为技术培训
            if("train".equals(trainType))
            {
            	
            	XSSFRow rowNext = sheet.getRow(j + 1);
            	String trainTypeNext = null;
            	if(null != rowNext)
            	{
            		trainTypeNext = null == rowNext.getCell(0) ? null : rowNext.getCell(0).toString().trim();
            	}
            	
            	// 下一条不存在或者下一条也为科技培训时，表示本条科技培训没有帮扶带动人信息，所以本条科技培训不做保存
            	if(null == rowNext || "train".equals(trainTypeNext))
            	{
            		if(null == noHelpMsg)
                	{
            			noHelpMsg = "第" + (j+1) + "行(区域编号：" + areaId + ")";
                	}
                	else
                	{
                		noHelpMsg += "," + (j + 1) + "行(区域编号：" + areaId + ")";
                	}
            		
            		continue;
            	}
            	
            	// 该条为技术培训时，保存所有上一次的扶贫人信息
            	if(null != trainList && trainList.size() > 0)
                {
                	 this.gtTrainPeopleService.insertList(trainList);
                	 trainList = new ArrayList<GtTrainPeople>();
                }
            	
            	Area area = this.areaService.get(areaId);
            	
            	if(null == trainInfo)
            	{
            		trainInfo = new GtTrain();
            	}
            	if(null == trainInfo.getArea())
            	{
            		Area trainArea = new Area();
                	trainInfo.setArea(trainArea);
            	}
            	
            	
            	String name = null == row.getCell(2) ? null : row.getCell(2).toString().trim();
            	String content = null == row.getCell(3) ? null : row.getCell(3).toString().trim();
            	String trainTime = null == row.getCell(4) ? null : row.getCell(4).toString().trim();
            	trainInfo.setIsNewRecord(true);
            	trainInfo.setId(IdGen.uuid());
            	trainInfo.setArea(area);
            	trainInfo.setName(name);
            	trainInfo.setContent(content);
            	try {
					trainInfo.setTrainTime(DateUtils.parseDate(trainTime, "yyyy-MM-dd HH:mm:ss"));
				} catch (ParseException e) {
					e.printStackTrace();
				}
            	trainInfo.setCreateBy(UserUtils.getUser());
            	trainInfo.setUpdateBy(UserUtils.getUser());
            	trainInfo.setCreateDate(new Date());
            	this.gtTrainService.save(trainInfo);
            	
            }
            else
            {
            	// 技术培训帮扶带动人口
            	// 经济林帮扶带动人口
            	String name = null == row.getCell(1) ? null : row.getCell(1).toString().trim();
            	if(null == name || "".equals(name))
            	{
            		continue;
            	}
            	String isHolder = null == row.getCell(2) ? null : row.getCell(2).toString().trim();
            	if(isHolder.length() > 1)
            	{
            		isHolder = isHolder.substring(0, 1);
            	}
            	String idCard = null == row.getCell(3) ? null : row.getCell(3).toString().trim();
            	if(idCard.length() > 22)
            	{
            		idCard = idCard.substring(0, 22);
            	}
            	String addr = null == row.getCell(4) ? null : row.getCell(4).toString().trim();
            	String helpType = null == row.getCell(5) ? null : row.getCell(5).toString().trim();
            	if(helpType.indexOf(".") > -1)
            	{
            		helpType = helpType.substring(0, 1);
            	}
            	helpType = helpType.replace("，", ",");
            	String helpOther = null == row.getCell(6) ? null : row.getCell(6).toString().trim();
            	GtTrainPeople trainPeople = new GtTrainPeople();
            	trainPeople.setId(IdGen.uuid());
            	trainPeople.setTrain(trainInfo);
            	trainPeople.setCreateBy(UserUtils.getUser());
            	trainPeople.setUpdateBy(UserUtils.getUser());
            	trainPeople.setName(name);
            	trainPeople.setIsHolder(isHolder);
            	trainPeople.setIdcard(idCard);
            	trainPeople.setAddress(addr);
            	trainPeople.setHelpType(helpType);
            	trainPeople.setCreateDate(new Date());
            	if("o".equals(helpType))
            	{
            		trainPeople.setHelpOther(helpOther);
            	}
            	trainList.add(trainPeople);
            	
            	if(trainList.size() > 500)
                {
                	 this.gtTrainPeopleService.insertList(trainList);
                	 trainList = new ArrayList<GtTrainPeople>();
                }
            }
            
        }
        
        if(null != trainList && trainList.size() > 0)
        {
        	 this.gtTrainPeopleService.insertList(trainList);
        }
        msg = "导入成功。";
        /*if(null != notTownAreaMsg)
		{
			msg += notTownAreaMsg + "技术培训信息的区域编码不是乡镇级别，不做导入处理；其所属帮扶带动人口信息也不做导入处理。";
		}*/
        
        if(null != noHelpMsg)
		{
			msg += noHelpMsg + "技术培训信息无帮扶带动人口，不做导入处理。";
		}
        
        return msg;
	}
	
	// 技术明白人信息导入
	public String importClear(XSSFSheet sheet)
	{
		String msg = "";
		// 区域编码不是区县或者乡镇
        String notCountyOrTownMsg = null;
        // 区域编码与技术类型不匹配
        String notMatchAreaAndTypeMsg = null;
        
		//创建行和列
        XSSFRow row;
		List<GtTecClear> clearList = new ArrayList<GtTecClear>();
		
		// 技术培训不做保存
		// boolean isContinue = false;
        for (int j = 2; j <= sheet.getLastRowNum(); j++) {
            row = sheet.getRow(j);
            
            String areaId = null == row.getCell(0) ? null : row.getCell(0).toString().trim();
            Area area = this.areaService.get(areaId);
            // 区域编码不是区县或者乡镇级别时，不做处理
        	if(null == area || Integer.parseInt(area.getType()) < 4)
        	{
        		if(null == notCountyOrTownMsg)
            	{
        			notCountyOrTownMsg = "第" + (j+1) + "行(区域编号：" + areaId + ")";
            	}
            	else
            	{
            		notCountyOrTownMsg += "," + (j + 1) + "行(区域编号：" + areaId + ")";
            	}
        		
        		continue;
        	}
            // 技术类别
        	String clearType = null == row.getCell(1) ? null : row.getCell(1).toString().trim();
        	
        	if(clearType.length() > 1)
        	{
        		clearType = clearType.substring(0, 1);
        	}
        	
        	if(!clearType.equals(area.getType()) && !Constant.Area.AREA_TYPE_VILLAGE.equals(clearType))
        	{
        		if(null == notMatchAreaAndTypeMsg)
            	{
        			notMatchAreaAndTypeMsg = "第" + (j+1) + "行(区域编号：" + areaId + ")";
            	}
            	else
            	{
            		notMatchAreaAndTypeMsg += "," + (j + 1) + "行(区域编号：" + areaId + ")";
            	}
        		
        		continue;
        	}
        	
        	String name = null == row.getCell(2) ? null : row.getCell(2).toString().trim();
        	if(null == name || "".equals(name))
        	{
        		continue;
        	}
        	String idCard = null == row.getCell(3) ? null : row.getCell(3).toString().trim();
        	String tel = null == row.getCell(4) ? null : row.getCell(4).toString().trim();
        	
        	if(tel.indexOf("E") > 0 || tel.indexOf("e") > 0)
        	{
        		tel = new BigDecimal(row.getCell(4).toString()).toString();
        	}
        	
        	if(tel.length() > 13)
        	{
        		tel = tel.substring(0, 13);
        	}
        	
        	String addr = null == row.getCell(5) ? null : row.getCell(5).toString().trim();
        	GtTecClear clear = new GtTecClear();
        	clear.setId(IdGen.uuid());
        	clear.setArea(area);
        	clear.setCreateBy(UserUtils.getUser());
        	clear.setUpdateBy(UserUtils.getUser());
        	clear.setType(clearType);
        	clear.setName(name);
        	clear.setIdcard(idCard);
        	clear.setTel(tel);
        	clear.setAddress(addr);
        	clear.setCreateDate(new Date());
        	clearList.add(clear);
        	
        	if(clearList.size() > 1000)
            {
            	 this.gtTecClearService.insertList(clearList);
            	 clearList = new ArrayList<GtTecClear>();
            }
            
        }
        
        if(null != clearList && clearList.size() > 0)
        {
        	 this.gtTecClearService.insertList(clearList);
        }
        msg = "导入成功。";
        
        if(null != notCountyOrTownMsg)
		{
			msg += notCountyOrTownMsg + "技术明白人信息区域编码不是区县或乡镇，不做导入处理。";
		}
        
        if(null != notMatchAreaAndTypeMsg)
		{
			msg += notMatchAreaAndTypeMsg + "技术明白人信息的区域编码和技术类别不匹配，不做导入处理。";
		}
        
        return msg;
	}
	
	// 护林员岗位信息导入
	public String importPost(XSSFSheet sheet)
	{
		String msg = "";
		// 区域编码不是区县或者乡镇
        String notTownMsg = null;
        
		//创建行和列
        XSSFRow row;
		List<GtPostPeople> postList = new ArrayList<GtPostPeople>();
		
        for (int j = 2; j <= sheet.getLastRowNum(); j++) {
            row = sheet.getRow(j);
            
            String areaId = null == row.getCell(0) ? null : row.getCell(0).toString().trim();
            Area area = this.areaService.get(areaId);
            // 区域编码不是乡镇级别时，不做处理
        	if(null == area || !area.getType().equals(Constant.Area.AREA_TYPE_TOWN))
        	{
        		if(null == notTownMsg)
            	{
        			notTownMsg = "第" + (j+1) + "行(区域编号：" + areaId + ")";
            	}
            	else
            	{
            		notTownMsg += "," + (j + 1) + "行(区域编号：" + areaId + ")";
            	}
        		
        		continue;
        	}
            // 技术类别
        	String name = null == row.getCell(1) ? null : row.getCell(1).toString().trim();
        	if(null == name || "".equals(name))
        	{
        		continue;
        	}
        	String isHolder = null == row.getCell(2) ? null : row.getCell(2).toString().trim();
        	if(isHolder.length() > 1)
        	{
        		isHolder = isHolder.substring(0, 1);
        	}
        	if(null != isHolder && isHolder.length() > 1)
        	{
        		System.out.println("=========================" +(j+1)+"行isHolder超长=================" + isHolder);
        	}
        	
        	
        	String idCard = null == row.getCell(3) ? null : row.getCell(3).toString().trim();
        	if(idCard.length() > 22)
        	{
        		idCard = idCard.substring(0, 22);
        	}
        	if(null != idCard && idCard.length() > 22)
        	{
        		System.out.println("=========================" +(j+1)+"行idcard超长=================" + idCard);
        	}
        	
        	String addr = null == row.getCell(4) ? null : row.getCell(4).toString().trim();
        	GtPostPeople post = new GtPostPeople();
        	post.setId(IdGen.uuid());
        	post.setArea(area);
        	post.setCreateBy(UserUtils.getUser());
        	post.setUpdateBy(UserUtils.getUser());
        	post.setName(name);
        	post.setIsHolder(isHolder);;
        	post.setIdcard(idCard);
        	post.setAddress(addr);
        	post.setCreateDate(new Date());
        	postList.add(post);
        	
        	if(postList.size() > 1000)
            {
            	 this.gtPostPeopleService.insertList(postList);
            	 postList = new ArrayList<GtPostPeople>();
            }
            
        }
        
        if(null != postList && postList.size() > 0)
        {
        	 this.gtPostPeopleService.insertList(postList);
        }
        msg = "导入成功。";
        
        if(null != notTownMsg)
		{
			msg += notTownMsg + "护林员岗位信息区域编码不是乡镇级，不做导入处理。";
		}
        
        return msg;
	}

	// 龙头企业（合作社）扶贫信息导入
	public String importCompany(XSSFSheet sheet)
	{
		String msg = "";
		
		// 没有帮扶带动人信息或者没有覆盖村信息
        String noHelpMsg = null;
        // 所填区域不是乡镇级别
        String notTownAreaMsg = null;
        
		//创建行和列
        XSSFRow row;
		List<GtCompanyPeople> companyPeopleList = new ArrayList<GtCompanyPeople>();
		GtCompany company = null;
		
		// 龙头企业（合作社）不做保存
		boolean isContinue = false;
        for (int j = 4; j <= sheet.getLastRowNum(); j++) {
            row = sheet.getRow(j);
            
            String areaId = null == row.getCell(1) ? null : row.getCell(1).toString().trim();
            
            // 类型：forest：龙头企业（合作社）；空：龙头企业（合作社）帮扶带动人口信息
            String companyType = null == row.getCell(0) ? null : row.getCell(0).toString().trim();
            // 该条信息为龙头企业（合作社）
            if("company".equals(companyType))
            {
            	XSSFRow rowNext = sheet.getRow(j + 1);
            	String companyTypeNext = null;
            	if(null != rowNext)
            	{
            		companyTypeNext = null == rowNext.getCell(0) ? null : rowNext.getCell(0).toString().trim();
            	}
            	
            	// 下一条不存在或者下一条也为龙头企业（合作社）时，表示本条龙头企业（合作社）没有帮扶带动人信息，所以本条龙头企业（合作社）不做保存
            	if(null == rowNext || "company".equals(companyTypeNext))
            	{
            		if(null == noHelpMsg)
                	{
            			noHelpMsg = "第" + (j+1) + "行(区域编号：" + areaId + ")";
                	}
                	else
                	{
                		noHelpMsg += "," + (j + 1) + "行(区域编号：" + areaId + ")";
                	}
            		
            		continue;
            	}
            	// 该条为龙头企业（合作社）时，保存所有上一次的扶贫人信息
            	if(null != companyPeopleList && companyPeopleList.size() > 0)
                {
                	 this.gtCompanyPeopleService.insertList(companyPeopleList);
                	 companyPeopleList = new ArrayList<GtCompanyPeople>();
                }
            	
            	Area area = this.areaService.get(areaId);
            	//不是乡镇级区域不做处理
            	if(!Constant.Area.AREA_TYPE_TOWN.equals(area.getType()))
                {
                	if(null == notTownAreaMsg)
                	{
                		notTownAreaMsg = "第" + (j+1) + "行(区域编号：" + areaId + ")";
                	}
                	else
                	{
                		notTownAreaMsg += "," + (j + 1) + "行(区域编号：" + areaId + ")";
                	}
                	
                	isContinue = true;
                	continue;
                }
            	else
            	{
            		isContinue = false;
            	}
            	
            	if(null == company)
            	{
            		company = new GtCompany();
            	}
            	if(null == company.getArea())
            	{
            		Area companyArea = new Area();
                	company.setArea(companyArea);
            	}
            	
            	
            	String name = null == row.getCell(2) ? null : row.getCell(2).toString().trim();
            	company.setIsNewRecord(true);
            	company.setId(IdGen.uuid());
            	company.setArea(area);
            	company.setName(name);
            	company.setCreateBy(UserUtils.getUser());
            	company.setUpdateBy(UserUtils.getUser());
            	company.setCreateDate(new Date());
            	this.gtCompanyService.save(company);
            	
            }
            else
            {
            	// 若龙头企业（合作社）跳过，则其下面的所有帮扶带动人都跳过
            	if(isContinue)
            	{
            		continue;
            	}
            	// 龙头企业（合作社）帮扶带动人口
            	String name = null == row.getCell(1) ? null : row.getCell(1).toString().trim();
            	if(null == name || "".equals(name))
            	{
            		continue;
            	}
            	String isHolder = null == row.getCell(2) ? null : row.getCell(2).toString().trim();
            	if(isHolder.length() > 1)
            	{
            		isHolder = isHolder.substring(0, 1);
            	}
            	String idCard = null == row.getCell(3) ? null : row.getCell(3).toString().trim();
            	if(idCard.length() > 22)
            	{
            		idCard = idCard.substring(0, 22);
            	}
            	String addr = null == row.getCell(4) ? null : row.getCell(4).toString().trim();
            	String helpType = null == row.getCell(5) ? null : row.getCell(5).toString().trim();
            	if(helpType.indexOf(".") > -1)
            	{
            		helpType = helpType.substring(0, 1);
            	}
            	helpType = helpType.replace("，", ",");
            	String helpOther = null == row.getCell(6) ? null : row.getCell(6).toString().trim();
            	GtCompanyPeople companyPeople = new GtCompanyPeople();
            	companyPeople.setId(IdGen.uuid());
            	companyPeople.setCompany(company);
            	companyPeople.setCreateBy(UserUtils.getUser());
            	companyPeople.setUpdateBy(UserUtils.getUser());
            	companyPeople.setName(name);
            	companyPeople.setIsHolder(isHolder);
            	companyPeople.setIdcard(idCard);
            	companyPeople.setAddress(addr);
            	companyPeople.setHelpType(helpType);
            	companyPeople.setCreateDate(new Date());
            	if("o".equals(helpType))
            	{
            		companyPeople.setHelpOther(helpOther);
            	}
            	companyPeopleList.add(companyPeople);
            	
            	if(companyPeopleList.size() > 500)
                {
                	 this.gtCompanyPeopleService.insertList(companyPeopleList);
                	 companyPeopleList = new ArrayList<GtCompanyPeople>();
                }
            }
            
        }
        
        if(null != companyPeopleList && companyPeopleList.size() > 0)
        {
        	 this.gtCompanyPeopleService.insertList(companyPeopleList);
        }
        msg = "导入成功。";
        if(null != notTownAreaMsg)
		{
			msg += notTownAreaMsg + "龙头企业（合作社）信息的区域编码不是乡镇级别，不做导入处理，其所属帮扶带动人口信息也不做导入处理。";
		}
        if(null != noHelpMsg)
		{
			msg += noHelpMsg + "龙头企业（合作社）信息无帮扶带动人口信息，不做导入处理。";
		}
        return msg;
	}
	
	// 信息宣传导入
	public String importDeliver(XSSFSheet sheet)
	{
		String msg = "";
		//创建行和列
        XSSFRow row;
		List<GtInfoDeliver> deliverList = new ArrayList<GtInfoDeliver>();
		
        for (int j = 2; j <= sheet.getLastRowNum(); j++) {
            row = sheet.getRow(j);
            
            String areaId = null == row.getCell(0) ? null : row.getCell(0).toString().trim();
            if(null == areaId || "".equals(areaId))
        	{
        		continue;
        	}
            Area area = this.areaService.get(areaId);
        	String title = null == row.getCell(1) ? null : row.getCell(1).toString().trim();
        	String content = null == row.getCell(2) ? null : row.getCell(2).toString().trim();
        	String mediaType = null == row.getCell(3) ? null : row.getCell(3).toString().trim();
        	String deliverTime = null == row.getCell(4) ? null : row.getCell(4).toString().trim();
        	GtInfoDeliver deliver = new GtInfoDeliver();
        	deliver.setId(IdGen.uuid());
        	deliver.setArea(area);
        	deliver.setCreateBy(UserUtils.getUser());
        	deliver.setUpdateBy(UserUtils.getUser());
        	deliver.setName(title);
        	deliver.setContent(content);
        	deliver.setMediaType(mediaType);
        	deliver.setCreateDate(new Date());
        	try {
				deliver.setDeliverTime(DateUtils.parseDate(deliverTime, "yyyy-MM-dd HH:mm:ss"));
			} catch (ParseException e) {
				e.printStackTrace();
			}
        	deliverList.add(deliver);
        	
        	if(deliverList.size() > 500)
            {
            	 this.gtInfoDeliverService.insertList(deliverList);
            	 deliverList = new ArrayList<GtInfoDeliver>();
            }
            
        }
        
        if(null != deliverList && deliverList.size() > 0)
        {
        	 this.gtInfoDeliverService.insertList(deliverList);
        }
        msg = "导入成功。";
        
        return msg;
	}
}